const Router = require('koa-router');
const router = new Router();
var url = require('url');
//var util = require('util');
var os = require('os');
var ip = require('ip');

//获取不到啊！以后再说
function getPublicIp() {
    var publicIp = null;
    try {
        var ifaces = os.networkInterfaces();
        console.log(ifaces);
        Object.keys(ifaces).forEach(function (ifname) {
            ifaces[ifname].forEach(function (iface) {
                if ('IPv4' !== iface.family || iface.internal !== false) {
                    // skip over internal (i.e. 127.0.0.1) and non-ipv4 addresses
                    console.log("skip over internal");
                    return;
                }
                if (!ip.isPrivate(iface.address)) {
                    publicIp = iface.address;
                }
            });
        });
    } catch (e) {
        console.log("Error! getPublicIp ");
    }
    return publicIp;
}

router.get('/getPublicIp', async (ctx, next) => {
    await next()

    ctx.body = {
        IP: getPublicIp()
    }
}
)

// 抄来的，可以独立放到 utils 下
// koa2 中调用是 req 为 ctx.req
const getClientIP = (req) => {
    return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
        req.connection.remoteAddress || // 判断 connection 的远程 IP
        req.socket.remoteAddress || // 判断后端的 socket 的 IP
        req.connection.socket.remoteAddress;
}

router.get('/globals', async (ctx, next) => {
    await next()

    // 解析 url 参数 ，解析不出来啊 ，结果是 null
    //但是  host 在 ctx.request.host
    //const params = url.parse(ctx.request.url, true).query;
    //console.log("params ===",params)

    console.log("url ===", ctx.url)

    const clientIP = getClientIP(ctx.req) // ctx.request.ip
    console.log("clientIP ===", clientIP)

    let results = {}
    results.host = ctx.request.host
    results.version = process.version
    results.filename = __filename
    results.dirname = __dirname
    results.uid = process.getuid
    results.clientIP = clientIP

    ctx.body = {
        status: 'success',
        //message: JSON.stringify(results),
        host :ctx.request.host,
        version : process.version,
        filename : __filename,
        dirname : __dirname,
        uid : process.getuid,
        clientIP : clientIP
    }
}
)

module.exports = router;
